package com.stars.easyms.datasource.util;

import com.stars.easyms.base.constant.CommonConstants;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * XmlMapper解析工具类
 *
 * @author guoguifang
 * @date 2018-10-19 10:07
 * @since 1.0.0
 */
public final class XmlMapperParseUtil {

    private static final String MAPPER_XML_SUFFIX = "/**/*Mapper.xml";

    public static void parse(SqlSessionFactory sqlSessionFactory, String resources) throws IOException {
        parse(sqlSessionFactory.getConfiguration(), resources);
    }

    public static void parse(Configuration configuration, String resources) throws IOException {
        for (String resource : StringUtils.tokenizeToStringArray(resources, CommonConstants.PROPERTIES_SEPARATOR)) {
            Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources(resource);
            for (Resource mapperLocation : mapperLocations) {
                if (mapperLocation != null) {
                    try {
                        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments());
                        xmlMapperBuilder.parse();
                    } catch (Exception e) {
                        throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);
                    } finally {
                        ErrorContext.instance().reset();
                    }
                }
            }
        }
    }

    public static List<String> convert(String packageName) {
        List<String> convertList = new ArrayList<>();
        for (String str : StringUtils.tokenizeToStringArray(packageName, CommonConstants.PROPERTIES_SEPARATOR)) {
            convertList.add(ResourceLoader.CLASSPATH_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(str) + MAPPER_XML_SUFFIX);
        }
        return convertList;
    }

    private XmlMapperParseUtil() {
    }
}
